package com.GatherFour;

import game.ghostleg.GhostLegAPI14newActivity;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class GameLobby extends Activity {
	private Button send_btn, start_btn;
	private EditText edText;
	private TextView chatbox; 
	private TextView[] playerName = new TextView[4];
	private Player user;
	private String address;
	private Socket outSocket, client;
	private ServerSocket inSocket;
	private String inMessage, outMessage;
	private Intent intent;
	protected Context context;
	private boolean firstTimeFlag = true; 
	private int playerNum;
	private String[] clientList;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_lobby);
		
		context = this.getApplicationContext();
		
		send_btn = (Button)findViewById(R.id.sendText);
		edText = (EditText)findViewById(R.id.inputText);
		playerName[0] = (TextView)findViewById(R.id.player1);
		playerName[1] = (TextView)findViewById(R.id.player2);
		playerName[2] = (TextView)findViewById(R.id.player3);
		playerName[3] = (TextView)findViewById(R.id.player4);
		chatbox = (TextView)findViewById(R.id.chatbox);
		chatbox.setText("");
		
		Bundle bundle = this.getIntent().getExtras();
		if(bundle.getString("self").equals("host")){
			user = new Player(bundle.getString("name"));
			user.setHostPlayer();
			user.playerID = 0;
			playerNum = bundle.getInt("clientNum")+1;
			clientList = bundle.getString("clientList").split("\\|");
			
			System.err.println(bundle.getString("clientList"));
			address = bundle.getString("address");
			playerName[0].setText(user.name);
			for(int j = 0; j< playerNum-1; j++){
				playerName[j+1].setText(clientList[j]);
			}

			
			new Thread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						inSocket = new ServerSocket(9000);
						while(true){
							client = inSocket.accept();
							Scanner in = new Scanner(client.getInputStream());
							if(in.hasNextLine()){
								inMessage = in.nextLine();
								runOnUiThread(updateChatbox);
							}
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}).start();
			hostInit();
			
			
			
		}else{
			user = new Player(bundle.getString("name"));
			user.setClientPlayer();
		
			
			address = bundle.getString("address");

			new Thread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						if(firstTimeFlag){
							inSocket = new ServerSocket(9001);
							firstTimeFlag = false;
						}
						while(true){
							client = inSocket.accept();
							Scanner in = new Scanner(client.getInputStream());
							if(in.hasNextLine()){
								inMessage = in.nextLine();
								if(inMessage.equals("nameList")){
									final String[] nameList = in.nextLine().split("\\|");
									System.err.println("NAMELIST"+nameList.length);
									runOnUiThread(new Runnable(){

										@Override
										public void run() {
											// TODO Auto-generated method stub
											for(int i = 0; i< nameList.length; i++){
												playerName[i].setText(nameList[i]);
											}
										}
										
									});
								}else if(inMessage.equals("0000gameStart")){
									
									intent = new Intent(context,GhostLegAPI14newActivity.class);
									
									Bundle bundle = new Bundle();
									bundle.putString("name", user.name);
									bundle.putString("self", "client");
									bundle.putString("hostAddr", address);
									intent.putExtras(bundle);
									startActivity(intent);
									
								}else{
									runOnUiThread(updateChatbox);
								}
							}
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}).start();
			clientInit();
		}
		
	//	manager.createGroup(channel, null);
		if(user.isHostPlayer()){
			start_btn = (Button)this.findViewById(R.id.startGameID);
			start_btn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
										
					new Thread(new Runnable(){

						@Override
						public void run() {
						try {
							outSocket = new Socket(address,9001);
							OutputStream out = outSocket.getOutputStream();
							String start_msg = "0000gameStart";
							out.write(start_msg.getBytes());
							outSocket.close();
						} catch (UnknownHostException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						}
					}).start();
					
					intent = new Intent(context,GhostLegAPI14newActivity.class);
					String[] c_address = new String[4];
					for(int i = 0 ; i < 4; i++){
						c_address[i] = address;
					}
					
					Bundle bundle = new Bundle();
					bundle.putString("name", user.name);
					bundle.putString("self", "host");
					bundle.putStringArray("clientAddr", c_address);
					intent.putExtras(bundle);
					startActivity(intent);
				}
				
			});
		}
		
	}
	
	public void hostInit(){
		send_btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				outMessage = edText.getText().toString();
				chatbox.append("\n"+outMessage);
				
				edText.setText("");
				new Thread(new Runnable(){

					@Override
					public void run() {
					try {
						outSocket = new Socket(address,9001);
						OutputStream out = outSocket.getOutputStream();
						out.write(outMessage.getBytes());
						outSocket.close();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
				}).start();
				
			}
			
		});
		
		new Thread(new Runnable(){

			@Override
			public void run() {
			try {
				outSocket = new Socket(address,9001);
				OutputStream out = outSocket.getOutputStream();
				String initMsg = getNameList();
				out.write(initMsg.getBytes());
				outSocket.close();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
		}).start();
	}
	
	public void clientInit(){
		send_btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				outMessage = edText.getText().toString();
				chatbox.append("\n"+outMessage);
				
				edText.setText("");
				new Thread(new Runnable(){
					@Override
					public void run() {
					try {
						outSocket = new Socket(address,9000);
						OutputStream out = outSocket.getOutputStream();
						out.write(outMessage.getBytes());
						outSocket.close();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
				
			}
			
		});

	}
	
	public Runnable updateChatbox = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			chatbox.append("\n"+inMessage);
		}
		
	};
	
	public String getNameList(){
		String result = "nameList\n"+user.name;
		for(int i = 0; i< playerNum-1 ; i++){
			result = result+"|"+clientList[i];
		}
			
		return result;
	}
}
